package com.freestyle.jms.common;

import com.freestyle.jmssample.api.pojo.SMSBean;
import com.freestyle.jmssample.rabbitmq.SMSConfig;
import com.freestyle.jmssample.rabbitmq.SMSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;

/**
 * Created by rocklee on 2022/1/7 15:42
 */
@Component
@Slf4j
public class RabbitMQEvent implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback{
  @Resource
  private SMSConfig smsConfig;

  /**
   * 消息发送成功的回调,当消息进入Exchange交换器时就进入回调,不管是否进入队列。
   * @param correlationData
   * @param ack
   * @param cause， ack=false时才有效
   */
  @Override
  public void confirm(CorrelationData correlationData, boolean ack, String cause) {
    log.info("============消息已发送至MQ服务器==========");
    SMSBean sms= smsConfig.getSMS(correlationData.getId());
    if (ack) {
      log.info("消息发送ACK成功"+(sms==null?"":":"+sms));
    } else {
      log.error("消息发送ACK失败，原因{}", cause);
      if (sms!=null) { //假如SMS不为空，则重新投到消息队列
      }
    }
  }

  /***
   * 当消息进入Exchange交换器后无法投入到指定的队列时触发
   * @param returnedMessage
   */
  @Override
  public void returnedMessage(ReturnedMessage returnedMessage) {
    log.info("============消息已发送至MQ服务器，但无法投到指定队列==========");
    SMSBean sms= smsConfig.getSMS(returnedMessage.getMessage().getMessageProperties().getMessageId());
    log.info("returnedMessage: replyCode:{},routerKey:{},{}",returnedMessage.getReplyCode(),returnedMessage.getRoutingKey(),
            sms);

  }
}
